import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  DeviceEventEmitter,
  NativeAppEventEmitter,
  Dimensions
} from 'react-native';

import * as config from '../../constants/apiConfig';
import styles from './editOrderStyle';
import helper from '../util/helper';
import api from '../../services/api';
import _ from 'lodash';
import Toast from 'react-native-sk-toast';
import DatePicker from 'react-native-datepicker';
import moment from 'moment';
import ToastTip from '../global/ToastTip';
import ImagePicker from 'react-native-image-picker';
import LoadingTip from '../global/LoadingTip';
import Touch from '../global/Touch';
import DeviceStorage from '../global/DeviceStorage';
import { Navigation } from '../global/navigation/index';

import KeyboardAwareScrollView from '../global/keyboardScrollView/KeyboardAwareScrollView';

const SAVE_ORDER_KEY = "@order@lockkey";
const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');
class EditLockkeyOrder extends Component {
    constructor(props) {
		super(props);

        let {data, source} = this.props;
        let serviceContentMap = {
            '保管钥匙':0,
            '送钥匙':1
        };
        let act = [0,0];
        if(source == 'edit'){
            act[serviceContentMap[data.lockkey_service_content]] = 1;
        }else {
            act = [1,0];
        }

		this.state = {
            isLoading: true,
			isRefreshing: false,
			currentPage: 1,
            addrContent:false,
            activeService:act,
            remarks:source=='edit'?(data.remarks||''):'',
            user_phone: source=='edit'?data.user_phone:(this.props.userPhone?this.props.userPhone:''),
            date: source=='edit'?moment(data.service_time).format('YYYY-MM-DD HH:mm'):moment().add(30,'minutes').format('YYYY-MM-DD HH:mm'),
            disableUpload:false,
            orderCreateSuccess:false,
		};

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    async _submitAction(){
        let {source, data} = this.props;

        let serviceContentMapS = {
            0:'保管钥匙',
            1:'送钥匙'
        };

        let {date, weixin, send_phone,service_time,to_address, user_phone, obj_name, obj_price,remarks, activeService,fileUri,fileData} = this.state;
        let req_data = {
            from_address:'',
            to_address:to_address||(source=='edit'?data.to_address:''),
            buy_address: '',
            service_type: 'lockkey',
            service_time: date||(source=='edit'?helper.returnTimeToStr(data.service_time):''),
            obj_name: '',
            obj_price: 0,
            phone: send_phone||(source=='edit'?data.phone:''),
            user_phone: user_phone,
            remarks:remarks,
            express_service_content: '',
            lockkey_service_content: serviceContentMapS[_.findIndex(activeService, function(o) { return o == 1;})],
            other_service_content:'',
            obj_image:'',
            start_location:'',
            dest_location: '',
            weixin: weixin||(source=='edit'?data.weixin:''),
        };

        if(source == 'edit'){
            req_data.id = data.id;
        }else{//创建时
            req_data.status = 1;
        }

        // if(!req_data.weixin){
        //     this.refs.toast.show('请输入业主微信号');
        //     return;
        // }
        //
        // if(req_data.weixin.length>16){
        //     this.refs.toast.show('业主微信号不能超过16个字符');
        //     return;
        // }

        if(!req_data.user_phone){
            this.refs.toast.show('请输入业主手机号');
            return;
        }

        if(!/^1[0-9]{10}$/.test(req_data.user_phone)){
            this.refs.toast.show('请输入正确的手机号');
            return;
        }

        if(!req_data.to_address){
            this.refs.toast.show('请输入服务地址');
            return;
        }

        if(req_data.to_address.length>70){
            this.refs.toast.show('服务地址不超过70个字符');
            return;
        }

        if(moment(req_data.service_time)-moment()<0){
            this.refs.toast.show('输入的时间需大于当前时间');
            return;
        }

        if(req_data.remarks.length>200){
            this.refs.toast.show('备注信息不能超过200个字符');
            return;
        }

        if(source != 'edit'){
            this.props.navigator.push({
                title: "确认提交订单",
    			screen: 'housekeeperapp.orderconfirm',
                backButtonTitle:'',
    			passProps: {
    				order_detail:req_data,
                    order_phone: this.props.userPhone,
                    fileUri:this.state.fileUri,
    			},
                navigatorStyle:{
                    tabBarHidden: true,
                    navBarTextColor: 'white',
                	navBarButtonColor: 'white',
                	navBarBackgroundColor: '#EA5404',
                    statusBarColor: '#EA5404',
                    navBarTitleTextCentered: true,
                    topBarElevationShadowEnabled:false
                },
                navigatorButtons: {
                    leftButtons:[
                        {
                            id: 'back',
                            icon: require("../../../img/hk_back_icon.png")
                        }
                    ]
                }
    		});
            return;
        }

        this.setState({loadingShow:true});

        req_data = {...req_data,remarkImage:fileData?fileData:''};
        console.log('test------------req_data',req_data);
        // let url = (source == 'edit'? '/order/updateorder':'/order/createorder');
        let res = await api.post('/order/updateorder',req_data);
        if(res.cd == 1){
            this.refs.toast.show(res.msg);
        }else{
            if(res.data){
                this.setState({loadingShow:false});

                Toast.bottom("编辑成功");
                setTimeout(() =>{
                    this.props.navigator.pop();
                    let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
                    Emitter.emit("order.onload");
                }, 500);
            }
        }

    }

    _selectAction(index){
        let temp = [0,0];
        temp[index] = 1;
        this.setState({ activeService:temp });
    }

    async _showUserAddrBtn(text){
        let phone = text || this.state.user_phone;
        console.log("$$$$$", phone);

        if(phone){
            let res = await api.post('/account/findUserByPhone',{phone});
            if(res && res.data){
                this.setState({addrContent:res.data.homeAddress});
            }
        }
    }

    _addressAction(){
        let {addrContent} = this.state;
        this.setState({
            to_address: addrContent
        });
    }

    componentDidMount(){
        let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        this._subcribOrder = Emitter.addListener('order.create_success', this._orderCreateSuccess.bind(this));
    }

    componentWillMount(){
        let {source,session} = this.props;
        if(source == 'edit'){
            return;
        }

        DeviceStorage.get(SAVE_ORDER_KEY).then((origin_data) =>{
            if(origin_data){
                let story = this.props.userPhone?Object.assign({},origin_data,{user_phone: this.props.userPhone}):origin_data;
                this.setState(story);
            }
            // if (session.user.productKey != "LiXiaoShuang") {
                this._showUserAddrBtn();
            // }
        });
    }

    _orderCreateSuccess(){
        this.setState({
            orderCreateSuccess:true,
        })
    }

    componentWillUnmount(){
        let {source} = this.props;
        let {date, user_phone, to_address, activeService, remarks} = this.state;
        let restory;
        if(this.props.userPhone){
            // user_phone = '';
            restory = {to_address, activeService, remarks};
        }else{
            restory = {user_phone, to_address, activeService, remarks};
        }

        source!='edit' && !this.state.orderCreateSuccess && DeviceStorage.save(SAVE_ORDER_KEY, restory);
        this._subcribOrder && this._subcribOrder.remove();
    }

    clearContent(){
        this.setState({
            date: moment().add(30,'minutes').format('YYYY-MM-DD HH:mm'),
            user_phone:'',
            to_address:'',
            activeService:[1,0,0],
            remarks:'',
            fileUri:'',
            fileData:'',
        });
    }

    _uploadImage(){
        this.setState({
            disableUpload:true,
        })
        this._getObj();
    }

    async _getObj() {
        var options = {
            title: "上传照片",
            cancelButtonTitle: "取消",
            takePhotoButtonTitle: "拍照",
            chooseFromLibraryButtonTitle: "选择相册",
            permissionDenied: {
                title: "提示",
                text: "没有拍照和获取相册权限",
                reTryTitle: "重试",
                okTitle: "确定"
            },
            mediaType:"photo",
            quality: 0.8,
            maxHeight: parseInt(deviceHeight*2),
            maxWidth: parseInt(deviceWidth*2),
            storageOptions: {
                skipBackup: true,
                path: "images"
            }
        };
        // 照片
        ImagePicker.showImagePicker(options, response => {
            this.setState({
                disableUpload:false,
            })
            // Same code as in above section!
            console.log('test======response',JSON.stringify(response));
            if (response.error) {
                console.log("ImagePicker Error: ", response.error);
            } else {
                if (response.didCancel) {
                    console.log("User cancelled image picker");
                    return;
                }
                console.log('test0000000000',response.uri);
                let fileData = "data:image/jpeg;base64," + response.data;
                this._completeUpload(response.uri,fileData);
            }
        });

        return false;
    }

    _completeUpload(fileUri,fileData){
        this.setState({
            fileUri:fileUri,
            fileData:fileData,
        });
    }
    _clearImage(){
        this.setState({
            fileUri:'',
            fileData:'',
        })
    }

    async _getNonPayment(){

        if (this.props.showTimes == 0) {//没有展示过

            let {source, data} = this.props;

            let {date,service_time,to_address, user_phone,remarks} = this.state;
            let req_data = {
                to_address:to_address||(source=='edit'?data.to_address:''),
                service_time: date||(source=='edit'?helper.returnTimeToStr(data.service_time):''),
                user_phone: user_phone,
                remarks:remarks,

            };
            
            if(!req_data.user_phone){
                this.refs.toast.show('请输入业主手机号');
                return;
            }

            if(!/^1[0-9]{10}$/.test(req_data.user_phone)){
                this.refs.toast.show('请输入正确的手机号');
                return;
            }

            if(!req_data.to_address){
                this.refs.toast.show('请输入服务地址');
                return;
            }

            if(req_data.to_address.length>70){
                this.refs.toast.show('服务地址不超过70个字符');
                return;
            }

            if(moment(req_data.service_time)-moment()<0){
                this.refs.toast.show('输入的时间需大于当前时间');
                return;
            }

            if(req_data.remarks.length>200){
                this.refs.toast.show('备注信息不能超过200个字符');
                return;
            }

            this.setState({loadingShow:true});
            let result = await api.post('/order/getNonPaymentOrder',{phone:user_phone});
            console.log('_getNonPayment',result);
            if (result.cd != 0) {
                Toast.bottom(result.msg);
                return;
            }
            if (result.data && result.data.length != 0) {//有欠费

                this.setState({loadingShow:false},() => {
                    let orderArrearageInfo = result.data[0];
                    this.props.onShowPayNotifyDialog(user_phone,orderArrearageInfo,result.data.length);
                });
                

            }else{//没有欠费
                this.setState({loadingShow:false},() => {
                    this._submitAction();
                });
            }
        }else{
            this.setState({loadingShow:false},() => {
                this._submitAction();
            });
        }
        


    }

    _clickImage(index){
        let {fileUri} = this.state;
        if (fileUri) {//有图片则预览
            this._previewPicture(fileUri)
            return;
        }
    }

    _previewPicture(fileUri){
        Navigation.startPreviewPictureActivity({"currentIndex":0,"fileUris":fileUri,"isUrl":true})
    }

    render() {
        let {data, source,session} = this.props;
        return (
            <View style={styles.wrapper}>
                <KeyboardAwareScrollView style={styles.container} extraScrollHeight={60}>
                    <View style={styles.formContainer}>

                        <View style={styles.formItem}>
                            <Text style={styles.leftText}>业主手机号</Text>
                            <TextInput
                                value={this.state.user_phone}
                                onChangeText={(text) =>{
                                    let p = text.replace(/ /g, '').substring(0,11);
                                    this.setState({user_phone: p, addrContent:false});
                                    if(p.length == 11){
                                        this._showUserAddrBtn(p);
                                    }
                                }}
                                style={[styles.itemRight, source=='edit'?{color:"#B5B5B5"}:{}]}
                                editable = {source=='edit'?false:true}
                                clearButtonMode={'while-editing'}
                                maxLength={13}
                                keyboardType={'numeric'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入业主手机号'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        </View>
                        <View style={styles.formItem}>
                            <Text style={styles.leftText}>服务地址</Text>
                            <TextInput
                                value={this.state.to_address}
                                defaultValue={source=='edit'?data.to_address:''}
                                onChangeText={(text) =>{this.setState({to_address:text})}}
                                style={styles.itemRight}
                                editable = {true}
                                multiline={Platform.OS=='ios'?false:true}
                                numberOfLines={1}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入服务地址'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                            {this.state.addrContent && session.user.productKey != "LiXiaoShuang"?
                            <TouchableOpacity onPress={this._addressAction.bind(this)}>
                                <Text style={styles.addressBtnText}>业主家</Text>
                            </TouchableOpacity>:null}
                        </View>

                        <View style={[styles.formItemSpri,{borderBottomWidth:0}]}>
                            <Text style={styles.leftText}>选择服务内容</Text>
                            <View style={styles.selectContent}>
                                <TouchableOpacity onPress={this._selectAction.bind(this,0)} style={styles.selectBtn}>
                                    <Text style={this.state.activeService[0]?styles.activeText:styles.notActiveText}>保管钥匙</Text>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={this._selectAction.bind(this,1)} style={styles.selectBtn}>
                                    <Text style={this.state.activeService[1]?styles.activeText:styles.notActiveText}>送钥匙</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                    <View style={styles.formContainer}>
                        <View style={styles.formItem}>
                            <Text style={styles.leftText}>服务时间</Text>
                                <DatePicker
                                    style={styles.centeDate}
                                    date={this.state.date}
                                    mode="datetime"
                                    format="YYYY-MM-DD HH:mm"
                                    minDate={moment().format('YYYY-MM-DD HH:mm')}
                                    // maxDate="2016-06-01"
                                    confirmBtnText="确定"
                                    cancelBtnText="关闭"
                                    showIcon={false}
                                    customStyles={{
                                      dateInput: {
                                        marginLeft: 0,
                                        alignItems: 'flex-start',
                                        borderWidth:0,
                                        },
                                      dateText:{
                                        textAlign: 'left',
                                    },
                                    btnTextCancel:{
                                        color: '#7B7B7B',
                                        fontSize: 15,
                                    },
                                    btnTextConfirm:{
                                        color: '#EA5404',
                                        fontSize:15
                                    },
                                    datePicker:{
                                        borderTopColor: '#DDDDDD',
                                        backgroundColor: '#fff',
                                    },
                                    datePickerCon:{
                                        backgroundColor: '#f3f3f3',
                                    }
                                    }}
                                    onDateChange={(date) => {this.setState({date: date})}}
                                  />
                        </View>
                        <View style={[styles.formItemRemark,{borderBottomWidth:0}]}>
                            <Text style={[styles.leftText,{marginTop:10}]}>备注信息</Text>
                            <TextInput
                                value={this.state.remarks}
                                defaultValue={source=='edit'?data.remarks:''}

                                onChangeText={(text)=>{this.setState({remarks:text})}}
                                style={[styles.itemRight,{height:88}]}

                                editable = {true}
                                multiline={Platform.OS=='ios'?false:true}
                                numberOfLines={4}
                                clearButtonMode={'while-editing'}
                                placeholder={'选填'}
                                underlineColorAndroid={'#ffffff'}
                                placeholderTextColor={'#B5B5B5'}
                                textAlignVertical={'top'} 
                            />
                            <TouchableOpacity
                                accessible={true}
                                activeOpacity={0.7}
                                onPress={ this._uploadImage.bind(this)}
                                disabled={this.state.disableUpload}
                            >
                                <Text
                                 style={[styles.actionBtn,{marginRight:10,marginTop:12}]}
                                >
                                    上传图片
                                </Text>
                            </TouchableOpacity>
                        </View>
                        {
                            this.state.fileUri?
                                <View style={styles.imageContanier}>
                                    <View style={styles.clearImageContainer}>
                                        <TouchableOpacity activeOpacity={0.7} onPress={this._clearImage.bind(this)} style={{height:30,height:30}}>
                                            <Image source={require('../../../img/close_icon.png')}  style={{marginRight:15,width:15,height:15}}/>
                                        </TouchableOpacity>
                                    </View>
                                    <TouchableOpacity activeOpacity={0.7} onPress={this._clickImage.bind(this)}>
                                        <Image source={{uri: this.state.fileUri}} resizeMode="contain" style={[styles.uploadAvatar,{marginTop:-7}]}/>
                                    </TouchableOpacity>
                                </View>
                            :
                            null
                        }
                    </View>
                </KeyboardAwareScrollView>
                <View style={styles.submitBtnContainer}>
                    <Touch onPress={this._getNonPayment.bind(this)} style={styles.submitBtn}>
                        <Text style={styles.submitBtnText}>确定</Text>
                    </Touch>
                </View>
                <ToastTip ref="toast" offsetY={160}/>
                <LoadingTip show={this.state.loadingShow}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
EditLockkeyOrder = connectHelper(state => state)(EditLockkeyOrder);

module.exports = EditLockkeyOrder;
